package com.hengxinguotong.zhihuichengjian.ui.engineering.task;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.ScheduleBean;
import com.hengxinguotong.zhihuichengjian.bean.ScheduleBeanRes;
import com.hengxinguotong.zhihuichengjian.bean.ScheduleRes;
import com.hengxinguotong.zhihuichengjian.bean.StructureBean;
import com.hengxinguotong.zhihuichengjian.bean.StructureRes;
import com.hengxinguotong.zhihuichengjian.treeview.Node;
import com.hengxinguotong.zhihuichengjian.treeview.NodeHelper;
import com.hengxinguotong.zhihuichengjian.treeview.NodeTreeAdapter;
import com.hengxinguotong.zhihuichengjian.treeview.ProjectScheduleTreeAdapter;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author wulei
 * @Date 2018/4/12
 *
 * 工程进度
 */

public class ProjectScheduleActivity extends BaseActivity implements View.OnClickListener,
        ProjectScheduleTreeAdapter.OnUpdateClickListener, ProjectScheduleTreeAdapter.OnFinishClickListener {
    @BindView(R.id.project_list)
    ListView projectList;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.has_authority)
    HXTextView hasAuthority;
    private LinkedList<Node> mLinkedList = new LinkedList<>();
    private ProjectScheduleTreeAdapter mAdapter;

    private boolean hasAffirm = false, hasUpdate = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_structure);
        ButterKnife.bind(this);

        hasAffirm = hasAffirm();
        hasUpdate = hasUpdate();
        initView();
    }

    private void initView(){
        titleTv.setText("工程进度");
        if(hasUpdate || hasAffirm){
            hasAuthority.setVisibility(View.VISIBLE);
        }
        mAdapter = new ProjectScheduleTreeAdapter(this,mLinkedList);
        projectList.setAdapter(mAdapter);
        mAdapter.setOnUpdateClickListener(this);
        mAdapter.setOnFinishClickListener(this);
        getProjectInfo(null);
    }

    private void getProjectInfo(String id) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            if(!Utils.isEmpty(id)){
                jsonObject.put("id", id);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(this, "/projectSchedule/loadTree/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {

                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    ScheduleRes scheduleRes = gson.fromJson(json, ScheduleRes.class);
                    if(scheduleRes.getStatus() == 1){
                        List<ScheduleBean> scheduleBeanList = scheduleRes.getValue();
                        if(scheduleBeanList.size() <= 0){
                            showToast("当前列表数据为空");
                        }else{
                            List<Node> data = addData(scheduleRes.getValue());
                            mLinkedList.addAll(NodeHelper.sortNodes(data));
                            mAdapter.notifyDataSetChanged();
                        }
                    }else{
                        showToast(scheduleRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }

    private List<Node> addData(List<ScheduleBean> datas){
        List<Node> data = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            data.add(datas.get(i));
        }
        return data;
    }

    @OnClick({R.id.iv_back})
    public void onClick(View v) {
        finish();
    }

    //弹窗dialog
    private void EdittextDialog(final Node node){
        final View view = LayoutInflater.from(this).inflate(R.layout.editbox_layout, null);//这里必须是final的
        final EditText edit=(EditText)view.findViewById(R.id.editText);//获得输入框对象

        new AlertDialog.Builder(this)
                .setTitle("请修改进度")//提示框标题
                .setView(view)
                .setPositiveButton("确定",//提示框的两个按钮
                        new android.content.DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                //事件
                                updatePercent(node, Float.parseFloat(edit.getEditableText().toString()));
                            }
                        }).setNegativeButton("取消", null).create().show();
    }

    //更新进度
    private void updatePercent(final Node node, float percent) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("id", node.get_id());
            jsonObject.put("isLeaf", node.getIsLeaf());
            jsonObject.put("percent", percent);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData((BaseActivity)this, "/projectSchedule/updatePercent/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {

                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    ScheduleBeanRes scheduleRes = gson.fromJson(json, ScheduleBeanRes.class);
                    if(scheduleRes.getStatus() == 1){
                        node.set_percent(scheduleRes.getValue().getPercent());
                        showToast("修改成功");
                        mAdapter.notifyDataSetChanged();
                    }else{
                        showToast(scheduleRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }

    @Override
    public void OnFinish(Node node) {
        if(hasAffirm){
            updatePercent(node, 100);
        }else{
            showToast("您没有该权限");
        }
    }

    @Override
    public void OnUpdate(Node node) {
        if(hasUpdate){
            EdittextDialog(node);
        }else{
            showToast("您没有该权限");
        }
    }
}
